from typing import Any

import requests


def WikipediaText(page_title: str, language: str = "zh") -> dict[str, Any]:
    try:
        # 维基百科API端点
        base_url = f"https://{language}.wikipedia.org/w/api.php"

        # API参数 - 特别添加explaintext参数获取纯文本
        params = {
            'action': 'query',
            'format': 'json',
            'titles': page_title,
            'prop': 'extracts|info',
            'exintro': 1,  # 只获取摘要
            'explaintext': 1,  # 关键参数：返回纯文本而非HTML
            'inprop': 'url',  # 获取页面URL
        }

        headers = {
            'User-Agent': 'MyWikiBot/1.0 (contact@mywebsite.com)'
        }

        response = requests.get(base_url, params=params, headers=headers, timeout=10)

        if response.status_code == 200:
            data = response.json()
            # 提取页面信息
            pages = data.get('query', {}).get('pages', {})
            page_id = next(iter(pages))  # 获取第一个页面的ID

            if page_id != '-1':  # 页面存在
                page_data = pages[page_id]
                return {
                    "success": True,
                    "title": page_data.get('title', ''),
                    "summary": page_data.get('extract', ''),
                    "url": page_data.get('fullurl', ''),
                    "pageid": page_id
                }
            else:
                return {
                    "success": False,
                    "error": "页面不存在"
                }
        else:
            return {
                "success": False,
                "error": f"API请求失败，状态码: {response.status_code}"
            }
    except requests.exceptions.RequestException as e:
        return {
            "success": False,
            "error": f"请求异常: {str(e)}"
        }

# 使用示例
if __name__ == "__main__":
    # 获取周恩来维基百科页面纯文本信息
    result = WikipediaText("纽约")

    print(result)

    if result["success"]:
        print(f"标题: {result['title']}")
        print(f"页面URL: {result['url']}")
        print("\n摘要内容:")
        print(result['summary'])
    else:
        print(f"错误: {result['error']}")